package com.haust.intercepter;

import com.haust.util.JWTUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: csp1999
 * @Date: 2020/08/28/17:54
 * @Description: 登录拦截器
 */
public class LoginIntercepter implements HandlerInterceptor {

    /*
     * @方法描述: 进入controller 进行拦截
     * @参数集合: [request, response, handler]
     * @返回类型: boolean
     * @作者名称: csp1999
     * @日期时间: 2020/8/28 17:57
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从url 参数中获取token
        String token = request.getParameter("token");

        // token 存在,则对其进行解密:
        if (token != null && token != "") {// 如果 header 中没有token
            Claims claims = JWTUtils.paraseJsonWebToken(token);

            if (claims != null) {
                String openid = (String) claims.get("openid");
                String name = (String) claims.get("name");
                String imgUrl = (String) claims.get("img");

                request.setAttribute("openid", openid);
                request.setAttribute("name", name);
                request.setAttribute("imgUrl", imgUrl);

                return true;// 放行
            }
        }
        response.sendRedirect("/xdclass/user/login");
        return false;// 拦截
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
